import gi
import sys
import emjs
import os
gi.require_version('Gtk','3.0')
from gi.repository import Gtk, Gdk
print(os.environ)
last_file_path=os.getenv('EMOJIII_LAST_USE_TEN')
class emj_builder:
    def __init__(self):
        print('emj builder init')

    def on_emj_click(self,widget):
        emj = widget.get_label()
        ## 复制
        Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).set_text(emj,-1)
        content = self.get_last_use_10_text()
        with open(last_file_path,'w') as f:
            content=content.replace(emj,'')
            content=emj+content
            if len(content) > 10:
                content = content[:10]
            f.write(content)

        self.flush_last_use_10()





    def get_last_use_10_text(self):
        with open(last_file_path,'r+') as f:
            content = f.read()
            f.seek(0)
            return content

    def flush_last_use_10(self):
        for c in self.last_use_10.get_children():
            self.last_use_10.remove(c)
        print(self.get_last_use_10_text())
        self.add_emoji_to_flowbox(flowbox=self.last_use_10,emjs=self.get_last_use_10_text())




    def get_last_use_10(self):
        self.last_use_10=self.build(emjs=self.get_last_use_10_text())
        return self.last_use_10


    def build(self,emjs=emjs.emjs.values()):
        print('building emojis...')
        flowbox = Gtk.FlowBox()
        flowbox.set_valign(Gtk.Align.START)
        flowbox.set_max_children_per_line(7)
        flowbox.set_selection_mode(Gtk.SelectionMode.NONE)
        self.add_emoji_to_flowbox(flowbox,emjs)
        return flowbox

    def add_emoji_to_flowbox(self,flowbox,emjs):
        print("add_emoji...emjs:%s"%emjs)
        for e in emjs:
            button = Gtk.Button.new_with_label(e)
            button.connect("clicked", self.on_emj_click)
            flowbox.add(button)
        flowbox.show_all()
